package com.junsi.framework.config;

import java.util.HashMap;
import java.util.Map;
import javax.sql.DataSource;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import com.alibaba.druid.pool.DruidDataSource;
import com.alibaba.druid.spring.boot.autoconfigure.DruidDataSourceBuilder;
import com.junsi.common.enums.DataSourceType;
import com.junsi.framework.config.properties.DruidProperties;
import com.junsi.framework.datasource.DynamicDataSource;

/**
 * druid 配置多数据源
 * 
 * @author junsi
 */
@Configuration
public class DruidConfig
{
    /***
     * masterDataSource 构建，url、username、password 读取 master 下的配置
     * <br/>@ConfigurationProperties 读取指定配置属性，注入到对应返回值中的属性
     * @param druidProperties 读取基础配置初始化
     * @return
     */
    @Bean
    @ConfigurationProperties("spring.datasource.druid.master")
    public DataSource masterDataSource(DruidProperties druidProperties)
    {
        DruidDataSource dataSource = DruidDataSourceBuilder.create().build();
        return druidProperties.dataSource(dataSource);
    }

    /***
     * slaveDataSource 构建，enabled、url、username、password 读取 slave 下的配置
     * <br/>@ConfigurationProperties 读取指定配置属性，注入到对应返回值中的属性
     * <br/>@ConditionalOnProperty 增加注入条件限制，满足指定属性值才会注入属性生效
     * @param druidProperties 读取基础配置初始化
     * @return
     */
    @Bean
    @ConfigurationProperties("spring.datasource.druid.slave")
    @ConditionalOnProperty(prefix = "spring.datasource.druid.slave", name = "enabled", havingValue = "true")
    public DataSource slaveDataSource(DruidProperties druidProperties)
    {
        DruidDataSource dataSource = DruidDataSourceBuilder.create().build();
        return druidProperties.dataSource(dataSource);
    }

    /***
     * 注入动态数据源
     * <br/>@Primary 自动装配时当出现多个Bean候选者时，被注解为@Primary的Bean将作为首选者，否则将抛出异常
     * @param masterDataSource
     * @param slaveDataSource
     * @return
     */
    @Bean(name = "dynamicDataSource")
    @Primary
    public DynamicDataSource dataSource(DataSource masterDataSource, DataSource slaveDataSource)
    {
        Map<Object, Object> targetDataSources = new HashMap<>();
        targetDataSources.put(DataSourceType.MASTER.name(), masterDataSource);
        targetDataSources.put(DataSourceType.SLAVE.name(), slaveDataSource);
        return new DynamicDataSource(masterDataSource, targetDataSources);
    }
}
